
var command_queue = [];
var command_timer = null; 

var callbacks = [];
var callback_keys = [];

function try_next_command() {
	if(null == command_timer) {
		command_timer = setTimeout(next_command, 10);
	}
}

function next_command() {
	var c = command_queue.shift();
	if (null == c) {
		//alert("no more commands");
		command_timer = null;
	} else {
		//alert(c);
		document.location = c;
		command_timer = setTimeout(next_command, 10);
	}
}

function queue_command(a) {
	var o = ['hook'];
	for (var i in a) {o.push(escape(a[i]));}
	command_queue.push(o.join(':'));
	try_next_command();
}

function debug_log(s) {
	var m = escape(s);
	queue_command(['log', s]);
}

function show(s) {
	queue_command(['alert', 'Alert', 'OK', s]);
}

function new_callback(k, f) {
	callbacks[k] = f;
}

function key_callback(c, k) {
	//debug_log("key callback " + k + " = " + c);
	callback_keys[k] = c;
}

function do_callback(k, a) {
	//debug_log("callback " + k);
	var c = callbacks[callback_keys[k]];
	callbacks[callback_keys[k]] = null;
	callback_keys[k] = null;
	if (null == c) { return; }
	c(a);
}

function pick_photo(k, c) {
	//var cf = c;
	//if (null == cf) { cf = function() { show("photo: " + k); } }
	new_callback(k, c);
	queue_command(['photo', 'library', k]);
}

function pick_music(k, c) {
	//var cf = c;
	//if (null == cf) { cf = function() { show("music: " + k); } }
	new_callback(k, c);
	queue_command(['music', 'choose', k]);
}
